import { takeEvery } from 'redux-saga'
import { put, call } from 'redux-saga/effects'
import batchFetch, { RequestOption } from '../service/baseAjaxService'
import { AJAX_CALL_SUCCESS, AJAX_CALL_FAIL, AJAX_CALL_START } from "../actions/AjaxAction"

/*export function fetchData(url, method, params) {
    return cFetch(url, method, params)
}*/

export function* executeAjax(action) {
    console.log("saga action", action);
    const {url, method, params} = action.playLoad;
    const requests: RequestOption[] = action.playLoad.requests;
    let batchRequests: RequestOption[] = [];
    requests.forEach((opt: RequestOption) => {
        batchRequests.push(opt);
    });
    try {
        const {response, error} = yield call(batchFetch, batchRequests);
        if (response) {
            yield put({
                type: AJAX_CALL_SUCCESS,
                data: response
            });
        } else {
            yield put({
                type: AJAX_CALL_FAIL,
                ...error
            })
        }
    } catch (error) {
        yield put({
            type: AJAX_CALL_FAIL,
            ...error
        })
    }

}

export function* watchAjax() {
    yield* takeEvery("AJAX_CALL_START", executeAjax)
}

